from django.shortcuts import render

# Create your views here.
# 导入:
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.http import JsonResponse
from django.views import View
from .models import OAuthQQUser
from django.contrib.auth import login
import logging
logger = logging.getLogger('django')
from oauth.utils import generate_access_token, check_access_token
import logging,json,re
from django_redis import get_redis_connection
from wangziye.models import User

class QQFirstView(View):
    """提供QQ登录页面网址"""

    def get(self, request):
        # next 表示从哪个页面进入到的登录页面
        # 将来登录成功后，就自动回到那个页面
        next = request.GET.get('next')

        # 获取 QQ 登录页面网址
        # 创建 OAuthQQ 类的对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        # 调用对象的获取 qq 地址方法
        login_url = oauth.get_qq_url()

        # 返回登录地址
        return JsonResponse({'errno': "0",
                             'errmsg': 'OK',
                             'login_url':login_url})

class QQSecondView(View):
    def get(self, request):

        code = request.GET.get('code')

        if not code:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少code参数'
            })

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 携带 code 向 QQ服务器 请求 access_token
            access_token = oauth.get_access_token(code)

            # 携带 access_token 向 QQ服务器 请求 openid
            openid = oauth.get_open_id(access_token)

        except Exception as e:
            # 如果上面获取 openid 出错, 则验证失败
            logger.error(e)
            # 返回结果
            return JsonResponse({'code': 400,
                                 'errmsg': 'oauth2.0认证失败, 即获取qq信息失败'})

        # 判断openid是否绑定用户
        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            # 如果openid没绑定用户
            # 加密openid，变成token
            access_token = generate_access_token(openid)
            return JsonResponse({
                'code': 300,
                'errmsg': 'ok',
                'access_token': access_token
            })
        else:
            # 根据user外键获取对应qq用户user
            user = oauth_qq.user

            # 实现状态保持
            login(request, user)

            # 创建response对象
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie('username', user.mobile, max_age=3600 * 24 * 14)
            return response

    def post(self, request):

        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')

        access_token = dict.get('access_token')

        if not all([mobile, password]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })
            # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入正确的手机号码'})

            # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入8-20位的密码'})

        redis_conn = get_redis_connection('verify_code')


        openid = check_access_token(access_token)
        if not openid:
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少openid'})
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        else:
            if not user.check_password(password):
                return JsonResponse({'code': 400,
                                     'errmsg': '密码不正确'})

        try:
            OAuthQQUser.objects.create(openid=openid, user=user)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '添加数据出错'})
        login(request, user)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response
